using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
using muduoDotNet.Common;

namespace muduoDotNet.Tests
{
    public class IntegrationTest
    {
        private readonly ITestOutputHelper _output;

        public IntegrationTest(ITestOutputHelper output)
        {
            _output = output;
        }

        [Fact]
        public void TestPerformanceCountersIntegration()
        {
            _output.WriteLine("TestPerformanceCountersIntegration started");
            
            // 重置计数器
            PerformanceCounters.ResetCounters();
            
            // 记录初始值
            var initialActiveConnections = PerformanceCounters.ActiveConnections;
            var initialTotalConnections = PerformanceCounters.TotalConnections;
            
            _output.WriteLine($"Initial Active Connections: {initialActiveConnections}");
            _output.WriteLine($"Initial Total Connections: {initialTotalConnections}");
            
            // 增加连接计数
            PerformanceCounters.IncrementActiveConnections();
            // 注意：IncrementActiveConnections()会同时增加ActiveConnections和TotalConnections
            
            _output.WriteLine($"After IncrementActiveConnections - Active: {PerformanceCounters.ActiveConnections}, Total: {PerformanceCounters.TotalConnections}");
            
            // 验证计数器更新
            Assert.Equal(initialActiveConnections + 1, PerformanceCounters.ActiveConnections);
            Assert.Equal(initialTotalConnections + 1, PerformanceCounters.TotalConnections);
            
            // 再增加一次总连接数
            PerformanceCounters.IncrementTotalConnections();
            
            _output.WriteLine($"After IncrementTotalConnections - Total: {PerformanceCounters.TotalConnections}");
            
            // 验证计数器更新
            Assert.Equal(initialTotalConnections + 2, PerformanceCounters.TotalConnections);
            
            // 增加数据传输计数
            PerformanceCounters.AddBytesSent(1024);
            PerformanceCounters.AddBytesReceived(512);
            
            // 验证数据传输计数
            Assert.Equal(1024, PerformanceCounters.BytesSent);
            Assert.Equal(512, PerformanceCounters.BytesReceived);
            
            // 增加事件循环计数
            PerformanceCounters.IncrementEventLoopIterations();
            PerformanceCounters.IncrementTasksExecuted();
            PerformanceCounters.IncrementTimersExecuted();
            
            _output.WriteLine($"EventLoopIterations: {PerformanceCounters.EventLoopIterations}");
            _output.WriteLine($"TasksExecuted: {PerformanceCounters.TasksExecuted}");
            _output.WriteLine($"TimersExecuted: {PerformanceCounters.TimersExecuted}");
            
            // 验证事件循环计数
            Assert.Equal(1, PerformanceCounters.EventLoopIterations);
            Assert.Equal(1, PerformanceCounters.TasksExecuted);
            Assert.Equal(1, PerformanceCounters.TimersExecuted);
            
            // 增加错误计数
            PerformanceCounters.IncrementTotalExceptions();
            PerformanceCounters.IncrementNetworkExceptions();
            PerformanceCounters.IncrementProtocolExceptions();
            
            _output.WriteLine($"TotalExceptions: {PerformanceCounters.TotalExceptions}");
            _output.WriteLine($"NetworkExceptions: {PerformanceCounters.NetworkExceptions}");
            _output.WriteLine($"ProtocolExceptions: {PerformanceCounters.ProtocolExceptions}");
            
            // 验证错误计数
            // 注意：IncrementNetworkExceptions()和IncrementProtocolExceptions()都会增加TotalExceptions
            Assert.Equal(3, PerformanceCounters.TotalExceptions);
            Assert.Equal(1, PerformanceCounters.NetworkExceptions);
            Assert.Equal(1, PerformanceCounters.ProtocolExceptions);
            
            // 记录处理时间
            PerformanceCounters.RecordProcessingTime(100);
            
            // 验证处理时间记录
            Assert.Equal(100, PerformanceCounters.TotalProcessingTimeMs);
            Assert.Equal(100, PerformanceCounters.MaxProcessingTimeMs);
            // 注意：MinProcessingTimeMs的初始值是long.MaxValue，第一次记录后会变成记录的值
            Assert.Equal(100, PerformanceCounters.MinProcessingTimeMs);
            
            // 获取性能报告
            var report = PerformanceCounters.GetPerformanceReport();
            Assert.NotNull(report);
            Assert.Contains("Performance Report:", report);
            
            _output.WriteLine("TestPerformanceCountersIntegration completed");
        }

        [Fact]
        public void TestConfigurationIntegration()
        {
            _output.WriteLine("TestConfigurationIntegration started");
            
            // 获取配置实例
            var config = Configuration.GetInstance();
            Assert.NotNull(config);
            
            // 测试获取默认值
            var bufferSize = config.GetValue<int>("network.buffer.size");
            Assert.Equal(64 * 1024, bufferSize);
            
            // 测试设置和获取自定义值
            config.SetValue("test.key", "test.value");
            var testValue = config.GetValue<string>("test.key");
            Assert.Equal("test.value", testValue);
            
            // 测试类型转换
            config.SetValue("test.int", "42");
            var testInt = config.GetValue<int>("test.int");
            Assert.Equal(42, testInt);
            
            _output.WriteLine("TestConfigurationIntegration completed");
        }

        [Fact]
        public void TestEndToEndIntegration()
        {
            _output.WriteLine("TestEndToEndIntegration started");
            
            // 重置性能计数器
            PerformanceCounters.ResetCounters();
            
            // 初始化配置
            var config = Configuration.GetInstance();
            config.SetValue("performance.connection.pool.enabled", true);
            config.SetValue("performance.connection.pool.min", 1);
            config.SetValue("performance.connection.pool.max", 3);
            config.SetValue("network.recovery.enabled", true);
            config.SetValue("network.reconnect.attempts", 2);
            config.SetValue("network.reconnect.interval.ms", 100);
            
            // 创建服务器和客户端
            var serverLoop = new EventLoop();
            var clientLoop = new EventLoop();
            var endPoint = new IPEndPoint(IPAddress.Loopback, 12346);
            
            var server = new TcpServer(serverLoop, endPoint);
            var client = new TcpClient(clientLoop, endPoint);
            
            // 验证模块集成
            Assert.NotNull(server.ConnectionPool);
            Assert.NotNull(client.RecoveryManager);
            
            // 启动服务器
            server.Start();
            
            // 启动服务器事件循环
            var serverTask = Task.Run(() => {
                try {
                    serverLoop.Start();
                }
                catch (Exception ex) {
                    _output.WriteLine($"Server loop exception: {ex.Message}");
                }
            });
            
            // 等待服务器启动
            Thread.Sleep(100);
            
            // 连接客户端
            client.Connect();
            
            // 启动客户端事件循环
            var clientTask = Task.Run(() => {
                try {
                    clientLoop.Start();
                }
                catch (Exception ex) {
                    _output.WriteLine($"Client loop exception: {ex.Message}");
                }
            });
            
            // 等待连接建立
            Thread.Sleep(100);
            
            // 验证连接已建立
            Assert.True(client.Connected);
            
            // 断开客户端连接
            client.Disconnect();
            
            // 等待断开连接
            Thread.Sleep(100);
            
            // 验证连接已断开
            Assert.False(client.Connected);
            
            // 停止服务器
            server.Stop();
            serverLoop.Stop();
            
            // 停止客户端
            clientLoop.Stop();
            
            // 等待任务完成，但设置超时
            try {
                if (!serverTask.Wait(2000)) {
                    _output.WriteLine("Server task timeout");
                }
            }
            catch (Exception ex) {
                _output.WriteLine($"Server task wait exception: {ex.Message}");
            }
            
            try {
                if (!clientTask.Wait(2000)) {
                    _output.WriteLine("Client task timeout");
                }
            }
            catch (Exception ex) {
                _output.WriteLine($"Client task wait exception: {ex.Message}");
            }
            
            // 清理资源
            client.Dispose();
            server.Dispose();
            clientLoop.Dispose();
            serverLoop.Dispose();
            
            _output.WriteLine("TestEndToEndIntegration completed");
        }
    }
}